<template>
  <el-dialog
    :close-on-click-modal="false"
    title="案件详情"
    :visible="detailsVisible"
    :before-close="onClose"
    width="60%"
  >
    <el-form ref="form" :model="form" label-width="120px" size="mini">
      <el-row>
        <el-col :span="12">
          <el-form-item label="案件号：">{{ form.case_number }}</el-form-item>
        </el-col>
        <el-col :span="12" style="padding-left: 10px;">
          <el-form-item label="保险公司">{{
            form.company_name
          }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="事故地址:">
            {{(form.province || '') +(form.city || '') +(form.area || '') +(form.accident_address || '') ||'暂无'}}
          </el-form-item>
        </el-col>
        <el-col :span="12" style="padding-left: 10px;">
          <el-form-item label="查勘员:">{{ form.surveyer }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="案件类型:">{{ caseTypeLabel }}</el-form-item>
        </el-col>
        <el-col :span="12" style="padding-left: 10px;">
          <el-form-item label="车牌号:">{{ form.car_number }}</el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="接单时间:">{{
            form.receiving_time
          }}</el-form-item>
        </el-col> -->
      </el-row>
      <el-row>
        <el-col :span="36">
          <el-form-item label="现场照片:">
            <el-upload
              class="load"
              action="#"
              :on-preview="handlePreview"
              :http-request="uploadImage"
              :on-change="handleChangeImg"
              :on-remove="handleRemove"
              :show-file-list="false"
              :file-list="fileList"
              multiple
              style="margin-left: 5px"
            >
              <el-button type="primary" size="mini">上传</el-button>
            </el-upload>
            <div
              v-for="(item, index) in imgArr"
              :key="index"
              style="
                position: relative;
                display: inline-block;
                margin-top: 10px;
              "
            >
              <el-image
                :src="item"
                :preview-src-list="getImgList(imgArr, index)"
                style="width: 80px; height: 80px; margin: 0 0 5px 5px"
              ></el-image>
              <i
                class="el-icon-circle-close"
                @click="removeImage(index)"
                style="
                  position: absolute;
                  top: 0;
                  right: 0;
                  cursor: pointer;
                  background-color: #fff;
                  padding: 2px;
                "
              ></i>
            </div>
            <!-- <el-upload
              action="#"
              :http-request="uploadImage"
              :on-change="handleChangeImg"
              list-type="picture-card"
              :file-list="fileList"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              multiple
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
              <img width="100%" :src="dialogImageUrl" alt="" />
            </el-dialog> -->
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="footer">
      <el-button @click="onClose">取 消</el-button>
      <!-- <el-button type="primary">提 交</el-button> -->
    </div>
  </el-dialog>
</template>

<script>
import { uploadImage, removeObject } from "@/utils/minio";
import {
  updateSurveyManagement,
  deleteSurveyImg,
} from "@/api/system/surveyManage";
export default {
  name: "caseDetailsEdit",
  components: {},
  data() {
    return {
      form: {},
      imgArr: [],
      newImgArr: [], // 新添加的照片数组
      fileName: "",
      fileList: [],
      dialogImageUrl: "",
      dialogVisible: false,
      caseTypeOptions: [
        { label: "工程机械类", value: 1 },
        { label: "房屋建筑类", value: 2 },
        { label: "道路设施类", value: 3 },
        { label: "电力/通讯设施类", value: 4 },
        { label: "园林绿化类", value: 5 },
        { label: "庄稼食品类", value: 6 },
        { label: "电器设备类", value: 7 },
        { label: "财产险物损类", value: 8 },
      ],
    };
  },
  props: {
    detailsVisible: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Object,
      default() {
        return {};
      },
    },
    imgList: {
      type: Array,
    },
  },
  computed: {
    caseTypeLabel() {
      const option = this.caseTypeOptions.find(
        (option) => option.value === this.form.case_type
      );
      return option ? option.label : "";
    },
  },
  watch: {
    formData(e) {
      this.form = {
        ...e,
      };
    },
    imgList(e) {
      this.fileList = e.map((item) => ({
        url: item.image_url,
        name: item.image_url.substring(item.image_url.lastIndexOf("/") + 1),
      }));
      this.imgArr = e.map((item) => item.image_url);
      console.log(this.fileList, this.imgArr);
    },
  },
  methods: {
    getImgList(e, index) {
      let arr = [];
      let i = 0;
      for (i; i < e.length; i++) {
        arr.push(e[i + index]);
        if (i + index >= e.length - 1) {
          index = 0 - (i + 1);
        }
      }
      return arr;
    },
    handleChangeImg(file, fileList) {},
    uploadImage(request) {
      uploadImage({
        file: request.file,
        onSuccess: (only) => {
          this.fileList.push(only);
          const newImgUrl = only.url.split("?")[0];
          this.imgArr.push(newImgUrl);
          this.newImgArr.push(newImgUrl); // 记录新上传的照片
          // this.imgArr = this.fileList.map((item) => item.url.split("?")[0]);
          updateSurveyManagement({
            case_number: this.form.case_number,
            imgList: this.imgArr,
          })
            .then(() => {
              this.$message.success("上传成功");
            })
            .catch((error) => {
              console.error("上传后端接口失败：", error);
              this.newImgArr.forEach((url) => {
                const fileName = url.substring(url.lastIndexOf("/") + 1);
                removeObject(
                  fileName,
                  () => {
                    console.log("对象已成功删除");
                  },
                  (err) => {
                    console.error("删除对象时出错：", err);
                  }
                );
              });
              this.newImgArr.forEach((url) => {
              const indexInFileList = this.fileList.findIndex(
                (file) => file.url.split("?")[0] === url
              );
              if (indexInFileList !== -1) {
                this.fileList.splice(indexInFileList, 1);
              }
              const indexInImgArr = this.imgArr.indexOf(url);
              if (indexInImgArr !== -1) {
                this.imgArr.splice(indexInImgArr, 1);
              }
            });
              this.newImgArr = []; // 清空新上传的照片数组
            });
        },
        onError: (err) => {
          console.error("Upload failed", err);
        },
      });
    },
    removeImage(index) {
      const file = this.fileList[index];
      const fileName = file.name;
      deleteSurveyImg({
        case_number: this.form.case_number,
        image_url: file.url,
      })
        .then((response) => {
          this.$modal.msgSuccess("删除成功");
          this.imgArr.splice(index, 1);
          this.fileList.splice(index, 1);
          removeObject(
            fileName,
            () => {
              console.log("对象已成功删除");
            },
            (err) => {
              console.error("删除对象时出错：", err);
            }
          );
          const index = this.fileList.findIndex(
            (item) => item.name === fileName
          );
          if (index !== -1) {
            this.fileList.splice(index, 1);
          }
        })
        .catch((error) => {
          console.error("删除图片时出错：", error);
        });
    },
    handlePreview(file) {
      // this.dialogImageUrl = file.url;
      // this.dialogVisible = true;
    },
    handleRemove(file, fileList) {
      // const fileName = file.name;
      // deleteSurveyImg({
      //   case_number: this.form.case_number,
      //   image_url: fileName,
      // })
      //   .then((response) => {
      //     this.$modal.msgSuccess("删除成功");
      //     this.minioClient.removeObject(this.bucketName, fileName, (err) => {
      //       if (err) {
      //         console.error("删除对象时出错：", err);
      //       } else {
      //         console.log("对象已成功删除", this.bucketName, fileName);
      //       }
      //     });
      //     const index = this.fileList.findIndex(
      //       (item) => item.name === fileName
      //     );
      //     if (index !== -1) {
      //       this.fileList.splice(index, 1);
      //     }
      //   })
      //   .catch((error) => {
      //     console.error("删除图片时出错：", error);
      //   });
    },
    onClose() {
      this.$emit("onClose");
    },
  },
};
</script>

<style scoped>
.footer {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
